-- UIHeroUpgradeRankEffect
-- Create by luohj Jan/19/2015
-- 英雄升阶光效界面

-- UIHeroUpgradeRankEffect继承自Layer
UIHeroUpgradeRankEffect = class("UIHeroUpgradeRank", function()
    return cc.Layer:create();
end);

function UIHeroUpgradeRankEffect.create(parameters, openType)
    return UIHeroUpgradeRankEffect.new(parameters, openType);
end

-- 模型缩放比例
local HERO_MODEL_SCALE = 0.6;

-- 显示英雄信息界面
function UIHeroUpgradeRankEffect:closeMe()
    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName("UIHeroUpgradeRankEffect");
end

-- 构造函数
function UIHeroUpgradeRankEffect:ctor(parameters, openType)
    -- 初始化
    self:setName("UIHeroUpgradeRankEffect");
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.info = parameters;
    if not openType then
        openType = "upgrade";
    end
    self.openType = openType;

    local node = cc.CSLoader:createNode("layout/hero/HeroUpgradeRankEffect.csb");
    self:addChild(node);
    self.node = node, "panel/txt";

    local CT = node:getChildByName("CT");
    self.CT = CT;

    -- 初始化view
    self:initView();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();

    -- 设置各文本控件的风格
    local kerning = 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning = -3;
    end
    local titleLabel = findChildByName(CT, "panel/txt");

    for i = 1,7 do
        local path = string.format("panel/prop/node%d/", i);
        local propTextNode = findChildByName(CT, path .. "txt");
        local propTextValNode = findChildByName(CT, path .. "txt_val");
        local propDescNode = findChildByName(CT, path .. "desc");
        TextStyleM.setTextStyle(propTextNode, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_BRIGHT_YELLOW, false, kerning);
        TextStyleM.setTextStyle(propTextValNode, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_BRIGHT_YELLOW, false, kerning);
        TextStyleM.setTextStyle(propDescNode, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_BRIGHT_YELLOW, false, kerning);
    end

    -- 注册任意地方点击返回事件
    local bgImage = findChildByName(self.node, "bg");
    local function onBgBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.isEnd then
                self.isEnd = true;

                local starNode = findChildByName(self.node, "CT/panel/star_node");
                local textNode = findChildByName(self.CT,"panel/txt");
                self:stopAllActions();
                starNode:stopAllActions();
                textNode:stopAllActions();

                local num = #self.labelList;
                for i = 1, num do
                    local label = self.labelList[i];
                    label:stopAllActions();
                end

                self:resetPosition();
                self:redraw();
            else
                UIMgr.getCurrentScene():removeFormByName("UIHeroUpgradeRankEffect");
            end
        end
    end
    bgImage:addTouchEventListener(onBgBackClick);
end

-- 重置界面各元素坐标
function UIHeroUpgradeRankEffect:resetPosition()
    local num = #self.labelList;
    for i = 1, num do
        local label = self.labelList[i];
        label:setPosition(label.initPosition);
    end

    local starNode = findChildByName(self.node, "CT/panel/star_node");
    starNode:removeAllChildren();
    starNode:setPosition(starNode.initPosition);

    local textNode = findChildByName(self.CT,"panel/txt");
    textNode:removeAllChildren()
    textNode:setPosition(textNode.initPosition);
end

-- 重绘
function UIHeroUpgradeRankEffect:redraw()
    -- 绘制标题
    local textNode = findChildByName(self.CT,"panel/txt");
    local str = getLocStr("level_up");
    if self.openType == "carving" then
        str = string.format(getLocStr("awake_carving"), PetM.query(self.info.classId, "short_name"));
    end

    local len = string.getWCharCount(str);
    local fontSize = 80 * getLocFontSizeMulti();

    resetEffectText(textNode);
    for i = 1, len do
        addEffectText(textNode, 0, 0, str, i, fontSize, "images/ui/text_mask/text_mask.png");
    end

    -- 绘制星星
    local starNum = self.info.starNum;
    local starPath = "images/ui/symbol/star_large.png";

    -- 如果冈布奥已觉醒，使用橙色的星星
    if AwakeM.isCarved(self.info.classId) then
        starPath = "images/ui/symbol/star_large3.png";
    end

    local starLayer = createStarLayer(starNum, starPath, "center", 0.3);
    local starNode = findChildByName(self.node, "CT/panel/star_node");
    starNode:removeAllChildren();
    starNode:addChild(starLayer);
    starNode:setVisible(true);

    -- 绘制属性
    local arr = self.info.arr;
    local index = 1;
    for _, value in pairs(arr) do
        local control = findChildByName(self.CT, "panel/prop/node" .. index);
        local descLabel = findChildByName(control, "desc");
        local nameLabel = findChildByName(control, "txt");
        local valueLabel = findChildByName(control, "txt_val");

        control:setPositionY(175 - index * 45);
        control:setVisible(false);
        descLabel:setVisible(false);
        nameLabel:setVisible(false);
        valueLabel:setVisible(false);

        if type(descLabel:getString()) == "string" and string.len(descLabel:getString()) > 0 then
            descLabel:setVisible(true);
            control:setOpacity(255);
            control:setVisible(true);
            index = index + 1;
        end
    end
end

-- 初始化视图
function UIHeroUpgradeRankEffect:initView()
    -- 属性变化table
    local arr = self.info.arr;

    local txt = findChildByName(self.CT,"panel/txt");
    txt.initPosition = cc.p(txt:getPosition());
    txt:setString(getLocStr("level_up"));
    if self.openType == "carving" then
        txt:setString(string.format(getLocStr("awake_carving"), PetM.query(self.info.classId, "short_name")));
    end

    local index = 1;
    self.labelList = {};
    for _, value in pairs(arr) do
        local control = findChildByName(self.CT, "panel/prop/node" .. index);
        control:setOpacity(0);
        control:setVisible(false);
        control.initPosition = cc.p(control:getPosition());
        if value[2] > 0 then
            local name = FieldsM.getFieldName(value[1]);
            if value[1] == "max_hp" then
                name = FieldsM.getFieldName("hp");
            elseif value[1] == "max_mp" then
                name = FieldsM.getFieldName("mp");
            elseif value[1] == "special_prop" then
                name = FormulaM.invoke("PET_SPECIAL_PROP_DESC", self.info.specialProp);
            elseif value[1] == "talent_skill_level" then
                name = getLocStr("talent_skill_level");
            elseif value[1] == "career_type" then
                name = string.format(getLocStr("open_career_type"), getNameByDep(value[2]));
            elseif value[1] == "fight_ability" then
                name = getLocStr("when_sky_combat") .. FieldsM.getFieldName("fight_ability");
            elseif value[1] == "fire" then
                name = getLocStr("when_sky_combat") .. FieldsM.getFieldName("fire");
            elseif value[1] == "armor" then
                name = getLocStr("when_sky_combat") .. FieldsM.getFieldName("armor");
            elseif value[1] == "speed" then
                name = getLocStr("when_sky_combat") .. FieldsM.getFieldName("speed");
            elseif value[1] == "luck" then
                name = getLocStr("when_sky_combat") .. FieldsM.getFieldName("luck");
            end

            local desc;
            if value[1] == "career_type" then
                desc = name;
            else
                desc = name .. " + " .. value[2];
            end

            local nameLabel = findChildByName(control, "txt");
            nameLabel:setVisible(false);

            local valueLabel = findChildByName(control, "txt_val");
            valueLabel:setVisible(false);

            local descLabel = findChildByName(control, "desc");
            descLabel:setVisible(true);
            descLabel:setString(desc);

            --[[if value[1] ~= "career_type" then
                local nameLabel = findChildByName(control, "txt");
                nameLabel:setString(name);

                local valueLabel = findChildByName(control, "txt_val");
                valueLabel:setString("+ " .. value[2]);

                local descLabel = findChildByName(control, "desc");
                descLabel:setVisible(false);
            else
                local nameLabel = findChildByName(control, "txt");
                nameLabel:setVisible(false);

                local valueLabel = findChildByName(control, "txt_val");
                valueLabel:setVisible(false);

                local descLabel = findChildByName(control, "desc");
                descLabel:setString(name);
            end]]

            index = index + 1;
            control:setVisible(true);
            table.insert(self.labelList, control);
        end
    end

    -- 星星组件
    local starNum = self.info.starNum;
    local starPath = "images/ui/symbol/star_large.png";

    -- 如果冈布奥已觉醒，使用橙色的星星
    if AwakeM.isCarved(self.info.classId) then
        starPath = "images/ui/symbol/star_large3.png";
    end
    local starLayer = createStarLayer(starNum, starPath, "center", 0.3);
    local starNode = findChildByName(self.node, "CT/panel/star_node");
    starNode.initPosition = cc.p(starNode:getPosition());
    starNode:addChild(starLayer);

    self.starList = {};
    local children = starLayer:getChildren();
    local len = table.getn(children)
    for i = 1, len do
        local child = children[i];
        child:setOpacity(0);
        table.insert(self.starList, child);
    end

    self:playEffect();
end

-- 注册事件处理回调函数
function UIHeroUpgradeRankEffect:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIHeroUpgradeRankEffect 界面析构清理");

            local UITrainingMain = UIMgr.getCurrentScene():getFormByName("UITrainingMain");
            if UITrainingMain then
                UITrainingMain:setVisible(true);
            end
        elseif ev == "enter" then
            local UITrainingMain = UIMgr.getCurrentScene():getFormByName("UITrainingMain");
            if UITrainingMain then
                UITrainingMain:setVisible(false);
            end
        end
    end);
end

-- 震动
function UIHeroUpgradeRankEffect:shake()
    local duration = 0.03;
    local offset = 6;

    local uiForm = UIMgr.getCurrentScene():getFormByName("UIHeroUpgradeRankEffect");
    if uiForm then
        local moveLeft = cc.MoveBy:create(duration, cc.p(-offset, 0));
        local moveDown = cc.MoveBy:create(duration, cc.p(0, -offset));
        local moveRight = cc.MoveBy:create(duration, cc.p(offset, 0));
        local moveUp = cc.MoveBy:create(duration, cc.p(0, offset));
        local action = cc.Sequence:create(moveLeft, moveDown, moveRight, moveUp);
        uiForm:runAction(cc.Repeat:create(action, 1));
        self:runAction(action:clone());
    end
end

-- 播放特效
function UIHeroUpgradeRankEffect:playEffect()
    local textNode = findChildByName(self.CT, "panel/txt");

    local str = textNode:getString();

    -- 音效
    --AudioM.playFx("title_gain");

    local function setActionEnd()
        self.isEnd = true;
    end

    -- 文字弹出
    local function playTextEffect()
        -- 属性提升出现
        local num = #self.labelList;
        for i = 1, num do
            local label = self.labelList[i];
            label:setPositionY(175 - i * 45 - 50);
            local labelDelay = cc.DelayTime:create( i * 0.2 );
            local move = cc.MoveTo:create(0.1, cc.p(label:getPositionX(), 175 - i * 45));
            label:runAction(cc.Sequence:create(labelDelay, cc.FadeIn:create(0.1), move));
        end

        performWithDelay(self, setActionEnd, (num + 1) * 0.2);
    end

    -- 星星飞入
    local starNode = findChildByName(self.node, "CT/panel/star_node");
    local starNum = self.info.starNum;
    local function playStarEffect()
        for i = 1, #self.starList do
            local icon = self.starList[i];
            local pos = cc.p(icon:getPosition());
            local delay = cc.DelayTime:create((i-1) * 0.3 + 0.1);

            local effect;
            local play = cc.CallFunc:create(function()
                local effectId = 1179;
                if self.openType == "carving" then
                    effectId = 1351;
                end
                _, effect = playEffect(icon, effectId, -10, -20);
            end);

            local delay2 = cc.DelayTime:create(0.4);
            local callFunc = cc.CallFunc:create(function()
                self:shake();
            end);
            local action1 = cc.Sequence:create(delay2, callFunc);

            local delay3 = cc.DelayTime:create(2);
            local callFunc2 = cc.CallFunc:create(function()
                effect:pause();
            end);
            local action2 = cc.Sequence:create(delay3, callFunc2);

            icon:runAction(cc.Sequence:create(delay, play, cc.Spawn:create(action1, action2)));
        end

        performWithDelay(self, playTextEffect, 0.8);
    end

    -- 标题飞入
    local function playFlyInEffect()
        local len = string.getWCharCount(str);
        local fontSize = 80 * getLocFontSizeMulti();
        local bgPath = "images/ui/text_mask/text_mask.png";

        -- 生成艺术字并旋转飞入
        genArtWordAndRotateFlyIn(textNode, fontSize, bgPath);
        performWithDelay(self, playStarEffect, 0.8);
    end

    playFlyInEffect();
end

function UIHeroUpgradeRankEffect:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    local bg = findChildByName(self.node, "bg");
    bg:setScaleX(bg:getScaleX() * 1.1);
    bg:setScaleY(bg:getScaleY() * 1.1);

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");
end

--获取底部菜单高度Y
function UIHeroUpgradeRankEffect:getBottomMenuHeightY()
    local h = cc.Director:getInstance():getOpenGLView():getFrameSize().height;
    return 86 * h / DESIGN_HEIGHT;
end

--获取底部菜单高度
function UIHeroUpgradeRankEffect:getBottomMenuHeight()
    local w = cc.Director:getInstance():getOpenGLView():getFrameSize().width;
    return 86 * w / DESIGN_WIDTH;
end

